﻿using Microsoft.Extensions.Configuration;

namespace Core.Extensions;

/// <summary>
/// 配置文件扩展类
/// </summary>
public static class ConfigurationsExtensions
{
    /// <summary>
    /// 获取全局的配置文件
    /// </summary>
    /// <param name="builder"></param>
    /// <param name="fileName">配置文件名；默认获取（appsettings.json）</param>
    /// <returns></returns>
    public static IConfiguration GetGlobalConfigurations(this IConfigurationBuilder builder, string fileName = "appsettings.json")
    {
        return builder
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile(fileName, optional: true, reloadOnChange: true)
            .Build();
    }

    /// <summary>
    /// 获取全局的配置
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    /// <param name="key">键值</param>
    /// <returns></returns>
    public static T GetGlobalSection<T>(string key)
    {
        return new ConfigurationBuilder().GetGlobalConfigurations().GetSection(key).Get<T>()!;
    }

    /// <summary>
    /// 获取自定义配置文件
    /// </summary>
    /// <param name="fileName">配置文件名称</param>
    /// <returns></returns>
    public static IConfigurationRoot AddJsonFile(string fileName)
    {
        var jsonFilePath = Path.Combine($"{fileName.Replace(".json", "")}.json");

        return new ConfigurationBuilder().AddJsonFile(jsonFilePath, false, true).Build();
    }
}
